package com.xiaochen.baidu.common.design.combination.engine;

import com.xiaochen.baidu.common.design.combination.logic.LogicFilter;
import com.xiaochen.baidu.common.design.combination.engine.model.aggregates.TreeRich;
import com.xiaochen.baidu.common.design.combination.engine.model.vo.EngineResult;
import com.xiaochen.baidu.common.design.combination.engine.model.vo.TreeNode;
import com.xiaochen.baidu.common.design.combination.engine.model.vo.TreeRoot;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author xc
 * @date 2025/10/11/15:45
 * @desc
 */
@Slf4j
public abstract class EngineBase<T> extends EngineConfig<T> implements IEngine<T> {
    
    public EngineBase(Map<String, LogicFilter<T>> stringLogicFilterMap) {
        super(stringLogicFilterMap);
    }

    @Override
    public abstract EngineResult process(Long treeId, TreeRich treeRich, Map<String, T> decisionMatter);
    
    protected TreeNode engineDecisionMaker(TreeRich treeRich, Long treeId, Map<String, T> decisionMatter){
        TreeRoot treeRoot = treeRich.getTreeRoot();
        Map<Long, TreeNode> treeNodeMap = treeRich.getTreeNodeMap();
        Long treeRootNodeId = treeRoot.getTreeRootNodeId();
        TreeNode treeNode = treeNodeMap.get(treeRootNodeId);
        //1为子叶节点，2为果实节点
        while (treeNode.getNodeType().equals(1)) {
            String ruleKey = treeNode.getRuleKey();
            LogicFilter<T> logicFilter = logicFilterMap.get(ruleKey);
            T matterValue = logicFilter.matterValue(treeId, decisionMatter);
            Long nextNodeId = logicFilter.filter(matterValue, treeNode.getTreeNodeLinkList());
            treeNode = treeNodeMap.get(nextNodeId);
            log.info("决策树引擎=>{} treeId：{} treeNode：{} ruleKey：{} matterValue：{} nextNodeId：{}",
                    treeRoot.getTreeName(),treeId, treeNode, ruleKey, matterValue, nextNodeId);
        }
        return treeNode;
    }
}
